import Vue from 'vue'
import VueRouter from 'vue-router'

Vue.use(VueRouter)

import Home from '@/views/home/Home.vue'
import Login from '@/views/login/Login.vue'
import Welcome from '@/views/welcome/Welcome.vue'
import User from '@/views/user/User.vue'
import Roles from '@/views/roles/Roles.vue'
import Rights from '@/views/rights/Rights.vue'
import Category from '@/views/category/Category.vue'
import Goods from '@/views/good/Goods.vue'
import addGoods from '@/views/good/addGoods.vue'
import Orders from '@/views/orders/Orders.vue'
import Reports from '@/views/reports/Reports.vue'
import Params from '@/views/params/Params.vue'
import store from '@/store/index'

const routes = [
  { path:'/',name:'home',component:Home,
    redirect:{
      path:'welcome'
    },
    children:[{
      name: 'Welcome',
      path: 'welcome',
      component: Welcome
    },{
      name:'User',
      path:'users',
      component: User
    },{
      name:'Rights',
      path:'rights',
      component:Rights
    },{
      name:'Roles',
      path:'roles',
      component:Roles
    },{
      name:'Category',
      path:'categories',
      component:Category
    },{
      name:'Goods',
      path:'goods',
      component:Goods
    },{
      name:'addGoods',
      path:'addgoods',
      component:addGoods
    },{
      name:'orders',
      path:'orders',
      component:Orders
    },{
      name:'Reports',
      path:'reports',
      component:Reports
    },{
      name:'params',
      path:'params',
      component:Params
    }
  ]
  },
  { path:'/login',name:'login',component:Login}
]

const router = new VueRouter({
  routes
})

//设置全局导航守卫
router.beforeEach((to,from,next)=>{
  console.log(to);
  //如果没有登录，但访问的是登录页面，则直接进入
  if(to.path==='/login'){
    next()
  }else{
    //验证token
    let resData = JSON.parse(localStorage.getItem('userName')) || []
    console.log(resData);
    //如果登录
    if(resData.token){
      next()
    }else{
      //没有登录，访问非登录页面则跳转到登录页面
      next('/login')
    }
  }
})

router.afterEach((to,from)=>{
  switch(to.path){
    case '/users':
      return store.state.tpath = '用户管理',store.state.ttpath='用户列表'
    case '/roles':
      return store.state.tpath = '权限管理',store.state.ttpath='角色列表'
    case '/rights':
      return store.state.tpath = '权限管理',store.state.ttpath='权限列表'
    case '/goods':
      return store.state.tpath = '商品管理',store.state.ttpath='商品列表'
    case '/categories':
      return store.state.tpath = '商品管理',store.state.ttpath='商品分类'
    case '/orders':
      return store.state.tpath = '订单管理',store.state.ttpath='订单列表'
    case '/reports':
      return store.state.tpath = '数据统计',store.state.ttpath='数据报表'
    case '/addGoods':
      return store.state.tpath = '商品管理',store.state.ttpath='添加商品'
    case '/params':
      return store.state.tpath = '商品管理',store.state.ttpath='分类参数'    
    default:
      return            
  }
})

export default router
